﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using IWshRuntimeLibrary;
using System.Windows.Forms;

namespace StayUnlocked
{
    public class Shortcut
    {
        public static void CreateStartupFolderShortcut()
        {
            var wshShell = new WshShellClass();
            var startUpFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

            var shortcut = (IWshShortcut)wshShell.CreateShortcut(startUpFolderPath + "\\Stay Unlocked!.lnk");
            shortcut.TargetPath = Application.ExecutablePath;
            shortcut.WorkingDirectory = Application.StartupPath;
            shortcut.Description = "Keeps your computer unlocked... until you say so";
            shortcut.Arguments = "minimize";
            shortcut.Save();
        }

        private static string GetShortcutTargetFile(string shortcutFilename)
        {
            var pathOnly = Path.GetDirectoryName(shortcutFilename);
            var filenameOnly = Path.GetFileName(shortcutFilename);

            var shell = new Shell32.ShellClass();
            var folder = shell.NameSpace(pathOnly);
            var folderItem = folder.ParseName(filenameOnly);
            if (folderItem != null)
            {
                var link = (Shell32.ShellLinkObject)folderItem.GetLink;
                return link.Path;
            }

            return String.Empty; // Not found
        }

        public static void DeleteStartupFolderShortcuts()
        {
            var startUpFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            var targetExeName = Application.ExecutablePath;
            var di = new DirectoryInfo(startUpFolderPath);
            var files = di.GetFiles("*.lnk");

            foreach (var fi in files)
            {
                var shortcutTargetFile = GetShortcutTargetFile(fi.FullName);
                if (shortcutTargetFile.EndsWith(targetExeName, StringComparison.InvariantCultureIgnoreCase))
                {
                    System.IO.File.Delete(fi.FullName);
                }
            }
        }

        public static bool StartupFolderShortcutExists()
        {
            var startUpFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
            var targetExeName = Application.ExecutablePath;
            var di = new DirectoryInfo(startUpFolderPath);
            var files = di.GetFiles("*.lnk");

            foreach (var fi in files)
            {
                var shortcutTargetFile = GetShortcutTargetFile(fi.FullName);
                if (shortcutTargetFile.EndsWith(targetExeName, StringComparison.InvariantCultureIgnoreCase))
                {
                    return true;
                }
            }
            return false;
        }
    }
}
